<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>题目管理 - 管理员端</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .page-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .page-title {
            font-size: 24px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin: 0;
        }

        .filters-bar {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
        }

        .filters-row {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .filter-label {
            font-size: 12px;
            color: #666;
            font-weight: 500;
        }

        .questions-table-container {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .table-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .table-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--neutral-dark);
            margin: 0;
        }

        .table-responsive {
            overflow-x: auto;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th {
            background: var(--neutral-light);
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: var(--neutral-dark);
            border-bottom: 1px solid var(--border-color);
        }

        .table td {
            padding: 15px;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }

        .question-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .question-icon {
            font-size: 24px;
            width: 40px;
            height: 40px;
            background: var(--primary-light);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .question-details h4 {
            margin: 0 0 4px 0;
            font-size: 16px;
            font-weight: 600;
            color: var(--neutral-dark);
        }

        .question-details p {
            margin: 0;
            font-size: 14px;
            color: #666;
        }

        .type-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .type-single {
            background: #e3f2fd;
            color: #1976d2;
        }

        .type-multiple {
            background: #fff3e0;
            color: #f57c00;
        }

        .type-judge {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-icon {
            width: 32px;
            height: 32px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            transition: all 0.2s ease;
        }

        .btn-view {
            background: #e3f2fd;
            color: #1976d2;
        }

        .btn-edit {
            background: #fff3e0;
            color: #f57c00;
        }

        .btn-delete {
            background: #ffebee;
            color: #d32f2f;
        }

        .btn-icon:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .pagination-container {
            padding: 20px;
            border-top: 1px solid var(--border-color);
            display: flex;
            justify-content: center;
        }

        .pagination {
            display: flex;
            gap: 8px;
            list-style: none;
            margin: 0;
            padding: 0;
        }

        .pagination li {
            display: inline-block;
        }

        .pagination a {
            display: block;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            color: var(--neutral-dark);
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .pagination a:hover {
            background: var(--primary-light);
            border-color: var(--primary);
        }

        .pagination .active a {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 16px;
            color: #ccc;
        }

        .empty-state p {
            margin: 0;
            font-size: 16px;
        }

        .loading {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        .loading-spinner {
            width: 32px;
            height: 32px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 16px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            backdrop-filter: blur(5px);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 800px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
            animation: modalSlideIn 0.3s ease;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--neutral-dark);
            margin: 0;
        }

        .btn-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #666;
            padding: 0;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--neutral-dark);
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-textarea {
            min-height: 100px;
            resize: vertical;
        }

        .modal-footer {
            padding: 20px 24px;
            border-top: 1px solid var(--border-color);
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }

        .btn-modal {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .btn-cancel {
            background: var(--neutral-light);
            color: var(--neutral-dark);
        }

        .btn-save {
            background: var(--primary);
            color: #000000;
            font-weight: 600;
        }

        .btn-save:hover {
            background: #4a5bb8;
            color: #000000;
        }

        .btn-modal:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        /* 表单提示样式 */
        .form-hint {
            margin-top: 8px;
            padding: 8px 12px;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            font-size: 13px;
            color: #6c757d;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.3s ease;
        }

        .form-hint i {
            font-size: 14px;
        }

        .form-hint.type-single {
            background: #e3f2fd;
            border-color: #2196f3;
            color: #1976d2;
        }

        .form-hint.type-multiple {
            background: #f3e5f5;
            border-color: #9c27b0;
            color: #7b1fa2;
        }

        .form-hint.type-true-false {
            background: #e8f5e8;
            border-color: #4caf50;
            color: #388e3c;
        }

        /* 表单组动画 */
        .form-group {
            transition: all 0.3s ease;
        }

        .form-group.hidden {
            opacity: 0;
            max-height: 0;
            overflow: hidden;
            margin: 0;
            padding: 0;
        }

        /* 模态框内容区域 */
        .modal-content {
            max-height: 90vh;
            overflow-y: auto;
        }

        /* 表单标签图标 */
        .form-label i {
            margin-right: 8px;
            font-size: 16px;
        }

        .sidebar-footer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 20px;
            border-top: 1px solid var(--border-color);
        }

        .logout-btn {
            width: 100%;
            padding: 12px 16px;
            background: var(--error-color);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            background: #c82333;
            transform: translateY(-1px);
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h3>管理员工作台</h3>
        </div>
        <ul class="sidebar-nav">
            <li class="nav-item">
                <a href="dashboard.html" class="nav-link">
                    <i>📊</i> 仪表盘
                </a>
            </li>
            <li class="nav-item">
                <a href="users.html" class="nav-link">
                    <i>👥</i> 用户管理
                </a>
            </li>
            <li class="nav-item">
                <a href="videos.html" class="nav-link">
                    <i>🎥</i> 视频管理
                </a>
            </li>
            <li class="nav-item">
                <a href="pending-videos.html" class="nav-link">
                    <i>📹</i> 待审核视频
                </a>
            </li>
            <li class="nav-item">
                <a href="exam-management.html" class="nav-link">
                    <i>📝</i> 考试管理
                </a>
            </li>
            <li class="nav-item">
                <a href="profile.html" class="nav-link">
                    <i>👤</i> 个人资料
                </a>
            </li>
        </ul>
        
        <!-- 退出登录 -->
        <div class="sidebar-footer">
            <button class="logout-btn" onclick="UserManager.logout()">
                <i>🚪</i> 退出登录
            </button>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <div class="content-wrapper">
            <div class="page-header">
                <h1 class="page-title">题目管理</h1>
                <div class="page-actions">
                    <button class="btn btn-primary" onclick="showCreateQuestionModal()">
                        <i>➕</i> 创建新题目
                    </button>
                </div>
            </div>

            <div class="filters-bar">
                <div class="filters-row">
                    <div class="filter-group">
                        <label class="filter-label">搜索</label>
                        <input type="text" class="form-control" placeholder="搜索题目..." id="searchInput">
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">类型</label>
                        <select class="form-control" id="typeFilter">
                            <option value="">全部类型</option>
                            <option value="1">单选题</option>
                            <option value="2">多选题</option>
                            <option value="3">判断题</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <button class="btn btn-secondary" onclick="searchQuestions()">🔍 搜索</button>
                    </div>
                </div>
            </div>

            <div class="questions-table-container">
                <div class="table-header">
                    <h3 class="table-title">题目列表</h3>
                    <div class="table-actions">
                        <span class="text-muted">共 <span id="totalQuestions">0</span> 个题目</span>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>题目信息</th>
                                <th>类型</th>
                                <th>难度</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="questionList">
                            <tr>
                                <td colspan="5" class="text-center">
                                    <div class="loading">加载中...</div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="pagination-container">
                    <ul class="pagination" id="pagination">
                        <!-- 分页按钮将在这里生成 -->
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- 侧边栏切换按钮 -->
    <button class="sidebar-toggle">☰</button>

    <!-- 创建/编辑题目模态框 -->
    <div class="modal" id="questionModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="modalTitle">创建新题目</h3>
                <button class="btn-close" onclick="hideQuestionModal()">&times;</button>
            </div>
            <form id="questionForm">
                <div class="form-group">
                    <label class="form-label" for="questionTitle">
                        <i>📝</i> 题目内容
                    </label>
                    <textarea class="form-control form-textarea" id="questionTitle" name="title" placeholder="请输入题目内容..." required></textarea>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="questionType">
                        <i>🏷️</i> 题目类型
                    </label>
                    <select class="form-control" id="questionType" name="type" required onchange="updateQuestionTypeHint()">
                        <option value="">请选择题目类型</option>
                        <option value="1">单选题</option>
                        <option value="2">多选题</option>
                        <option value="3">判断题</option>
                    </select>
                    <div class="form-hint" id="typeHint">
                        <i>💡</i> 请先选择题目类型
                    </div>
                </div>
                
                <div class="form-group" id="optionsGroup">
                    <label class="form-label" for="questionOptions">
                        <i>📋</i> 选项设置
                    </label>
                    <textarea class="form-control form-textarea" id="questionOptions" name="options" placeholder="A. 选项1&#10;B. 选项2&#10;C. 选项3&#10;D. 选项4"></textarea>
                    <div class="form-hint" id="optionsHint">
                        <i>💡</i> 每行一个选项，格式：A. 选项内容
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="questionAnswer">
                        <i>✅</i> 正确答案
                    </label>
                    <input type="text" class="form-control" id="questionAnswer" name="answer" placeholder="请输入正确答案" required>
                    <div class="form-hint" id="answerHint">
                        <i>💡</i> 请输入正确答案
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="questionDifficulty">
                        <i>⚡</i> 难度等级
                    </label>
                    <select class="form-control" id="questionDifficulty" name="difficulty" required>
                        <option value="">请选择难度</option>
                        <option value="1">简单</option>
                        <option value="2">中等</option>
                        <option value="3">困难</option>
                    </select>
                </div>
            </form>
            <div class="modal-footer">
                <button class="btn-modal btn-cancel" onclick="hideQuestionModal()">
                    <i>❌</i> 取消
                </button>
                <button class="btn-modal btn-save" onclick="saveQuestion()">
                    <i>💾</i> 保存
                </button>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let questions = [];
        let currentQuestionId = null;
        let isEditMode = false;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadQuestions();
        });

        // 检查用户权限
        async function checkAuth() {
            const user = await UserManager.init();
            if (!user || user.role !== 0) {
                Message.error('请先登录管理员账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return;
            }
        }

        // 加载题目列表
        async function loadQuestions() {
            try {
                const response = await API.get('/question/admin/all');
                if (response.success) {
                    questions = response.questions || [];
                    renderQuestionList();
                } else {
                    Message.error(response.message || '加载题目列表失败');
                    showEmptyState();
                }
            } catch (error) {
                console.error('加载题目列表失败:', error);
                Message.error('加载题目列表失败，请稍后重试');
                showEmptyState();
            }
        }

        // 渲染题目列表
        function renderQuestionList() {
            const questionList = document.getElementById('questionList');

            if (questions.length === 0) {
                showEmptyState();
                return;
            }

            questionList.innerHTML = questions.map(question => {
                // 使用后端实际的字段名
                const typeClass = getTypeClass(question.type || 1);
                const typeText = getTypeText(question.type || 1);
                const difficultyText = getDifficultyText(question.difficulty);
                
                // 构建选项文本
                const options = [];
                if (question.optionA) options.push(`A. ${question.optionA}`);
                if (question.optionB) options.push(`B. ${question.optionB}`);
                if (question.optionC) options.push(`C. ${question.optionC}`);
                if (question.optionD) options.push(`D. ${question.optionD}`);
                const optionsText = options.length > 0 ? options.join('\n') : '暂无选项';

                return `
                    <tr>
                        <td>
                            <div class="question-info">
                                <div class="question-icon">❓</div>
                                <div class="question-details">
                                    <h4>${question.content || '无题目内容'}</h4>
                                    <p style="white-space: pre-line;">${optionsText}</p>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="type-badge ${typeClass}">${typeText}</span>
                        </td>
                        <td>${difficultyText}</td>
                        <td>${formatDate(question.createTime)}</td>
                        <td>
                            <div class="action-buttons">
                                <button class="btn-icon btn-view" onclick="viewQuestion(${question.id})" title="查看详情">
                                    👁️
                                </button>
                                <button class="btn-icon btn-edit" onclick="editQuestion(${question.id})" title="编辑">
                                    ✏️
                                </button>
                                <button class="btn-icon btn-delete" onclick="deleteQuestion(${question.id})" title="删除">
                                    🗑️
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
            }).join('');

            document.getElementById('totalQuestions').textContent = questions.length;
        }

        // 显示空状态
        function showEmptyState() {
            const questionList = document.getElementById('questionList');
            questionList.innerHTML = `
                <tr>
                    <td colspan="5" class="text-center">
                        <div class="empty-state">
                            <i>❓</i>
                            <p>暂无题目数据</p>
                        </div>
                    </td>
                </tr>
            `;
            document.getElementById('totalQuestions').textContent = '0';
        }

        // 获取类型样式类
        function getTypeClass(type) {
            switch (type) {
                case 1: return 'type-single';
                case 2: return 'type-multiple';
                case 3: return 'type-judge';
                default: return 'type-single';
            }
        }

        // 获取类型文本
        function getTypeText(type) {
            switch (type) {
                case 1: return '单选题';
                case 2: return '多选题';
                case 3: return '判断题';
                default: return '未知';
            }
        }

        // 获取难度文本
        function getDifficultyText(difficulty) {
            switch (difficulty) {
                case 1: return '简单';
                case 2: return '中等';
                case 3: return '困难';
                default: return '未知';
            }
        }

        // 格式化日期
        function formatDate(timestamp) {
            if (!timestamp) return '';
            const date = new Date(timestamp);
            return date.toLocaleString('zh-CN');
        }

        // 显示创建题目模态框
        function showCreateQuestionModal() {
            isEditMode = false;
            currentQuestionId = null;
            document.getElementById('modalTitle').textContent = '创建新题目';
            document.getElementById('questionForm').reset();
            document.getElementById('questionModal').style.display = 'flex';
            updateQuestionTypeHint(); // 初始化提示信息
        }

        // 更新题目类型提示信息
        function updateQuestionTypeHint() {
            const questionType = document.getElementById('questionType').value;
            const typeHint = document.getElementById('typeHint');
            const optionsHint = document.getElementById('optionsHint');
            const answerHint = document.getElementById('answerHint');
            const optionsGroup = document.getElementById('optionsGroup');
            const questionOptions = document.getElementById('questionOptions');
            const questionAnswer = document.getElementById('questionAnswer');

            // 清除所有提示样式
            typeHint.className = 'form-hint';
            optionsHint.className = 'form-hint';
            answerHint.className = 'form-hint';

            switch (questionType) {
                case '1': // 单选题
                    typeHint.innerHTML = '<i>💡</i> 单选题：学生只能选择一个答案';
                    typeHint.className = 'form-hint type-single';
                    
                    optionsHint.innerHTML = '<i>💡</i> 每行一个选项，格式：A. 选项内容<br>例如：A. 选项1<br>B. 选项2<br>C. 选项3<br>D. 选项4';
                    optionsHint.className = 'form-hint type-single';
                    
                    answerHint.innerHTML = '<i>💡</i> 请输入正确答案的选项字母，如：A、B、C、D';
                    answerHint.className = 'form-hint type-single';
                    
                    questionOptions.placeholder = 'A. 选项1\nB. 选项2\nC. 选项3\nD. 选项4';
                    questionAnswer.placeholder = '请输入正确答案（如：A）';
                    optionsGroup.style.display = 'block';
                    break;

                case '2': // 多选题
                    typeHint.innerHTML = '<i>💡</i> 多选题：学生可以选择多个答案';
                    typeHint.className = 'form-hint type-multiple';
                    
                    optionsHint.innerHTML = '<i>💡</i> 每行一个选项，格式：A. 选项内容<br>例如：A. 选项1<br>B. 选项2<br>C. 选项3<br>D. 选项4';
                    optionsHint.className = 'form-hint type-multiple';
                    
                    answerHint.innerHTML = '<i>💡</i> 请输入正确答案的选项字母组合，如：AB、ACD、ABCD';
                    answerHint.className = 'form-hint type-multiple';
                    
                    questionOptions.placeholder = 'A. 选项1\nB. 选项2\nC. 选项3\nD. 选项4';
                    questionAnswer.placeholder = '请输入正确答案（如：AB、ACD）';
                    optionsGroup.style.display = 'block';
                    break;

                case '3': // 判断题
                    typeHint.innerHTML = '<i>💡</i> 判断题：学生选择正确或错误';
                    typeHint.className = 'form-hint type-true-false';
                    
                    optionsHint.innerHTML = '<i>💡</i> 判断题不需要设置选项，系统会自动提供"正确"和"错误"选项';
                    optionsHint.className = 'form-hint type-true-false';
                    
                    answerHint.innerHTML = '<i>💡</i> 请输入正确答案：T（正确）或 F（错误）';
                    answerHint.className = 'form-hint type-true-false';
                    
                    questionOptions.placeholder = '判断题不需要设置选项';
                    questionAnswer.placeholder = '请输入正确答案（T 或 F）';
                    optionsGroup.style.display = 'none';
                    break;

                default:
                    typeHint.innerHTML = '<i>💡</i> 请先选择题目类型';
                    optionsHint.innerHTML = '<i>💡</i> 每行一个选项，格式：A. 选项内容';
                    answerHint.innerHTML = '<i>💡</i> 请输入正确答案';
                    questionOptions.placeholder = 'A. 选项1\nB. 选项2\nC. 选项3\nD. 选项4';
                    questionAnswer.placeholder = '请输入正确答案';
                    optionsGroup.style.display = 'block';
                    break;
            }
        }

        // 编辑题目
        function editQuestion(questionId) {
            const question = questions.find(q => q.id === questionId);
            if (!question) {
                Message.error('题目不存在');
                return;
            }

            isEditMode = true;
            currentQuestionId = questionId;
            document.getElementById('modalTitle').textContent = '编辑题目';
            document.getElementById('questionTitle').value = question.content || '';
            document.getElementById('questionType').value = question.type || 1;
            document.getElementById('questionAnswer').value = question.correctAns || '';
            document.getElementById('questionDifficulty').value = question.difficulty || 1;
            
            // 构建选项文本
            const options = [];
            if (question.optionA) options.push(`A. ${question.optionA}`);
            if (question.optionB) options.push(`B. ${question.optionB}`);
            if (question.optionC) options.push(`C. ${question.optionC}`);
            if (question.optionD) options.push(`D. ${question.optionD}`);
            document.getElementById('questionOptions').value = options.join('\n');
            
            document.getElementById('questionModal').style.display = 'flex';
            updateQuestionTypeHint(); // 更新提示信息
        }

        // 查看题目详情
        function viewQuestion(questionId) {
            const question = questions.find(q => q.id === questionId);
            if (!question) {
                Message.error('题目不存在');
                return;
            }

            // 构建选项文本
            const options = [];
            if (question.optionA) options.push(`A. ${question.optionA}`);
            if (question.optionB) options.push(`B. ${question.optionB}`);
            if (question.optionC) options.push(`C. ${question.optionC}`);
            if (question.optionD) options.push(`D. ${question.optionD}`);
            const optionsText = options.length > 0 ? options.join('\n') : '无选项';

            alert(`题目详情：\n\n${question.content || '无题目内容'}\n\n选项：\n${optionsText}\n\n正确答案：${question.correctAns || '无'}`);
        }

        // 隐藏模态框
        function hideQuestionModal() {
            document.getElementById('questionModal').style.display = 'none';
        }

        // 保存题目
        async function saveQuestion() {
            const form = document.getElementById('questionForm');
            const formData = new FormData(form);
            
            // 解析选项文本
            const optionsText = formData.get('options') || '';
            const options = optionsText.split('\n').map(opt => opt.trim()).filter(opt => opt);
            
            // 构建后端期望的Question对象
            const questionData = {
                content: formData.get('title'), // 题目内容
                optionA: options[0] ? options[0].replace(/^[A-D]\.\s*/, '') : '',
                optionB: options[1] ? options[1].replace(/^[A-D]\.\s*/, '') : '',
                optionC: options[2] ? options[2].replace(/^[A-D]\.\s*/, '') : '',
                optionD: options[3] ? options[3].replace(/^[A-D]\.\s*/, '') : '',
                correctAns: formData.get('answer'),
                type: parseInt(formData.get('type')) || 1,
                difficulty: parseInt(formData.get('difficulty')) || 1,
                category: '默认分类',
                teacherId: UserManager.getUserId() // 获取当前用户ID
            };

            try {
                let response;
                if (isEditMode) {
                    response = await API.put(`/question/admin/update/${currentQuestionId}`, questionData);
                } else {
                    response = await API.post('/question/admin/create', questionData);
                }

                if (response.success) {
                    Message.success(response.message);
                    hideQuestionModal();
                    loadQuestions();
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('保存题目失败:', error);
                Message.error('保存题目失败，请稍后重试');
            }
        }

        // 删除题目
        async function deleteQuestion(questionId) {
            if (!confirm('确定要删除这个题目吗？此操作不可恢复！')) return;

            try {
                const response = await API.delete(`/question/admin/delete/${questionId}`);
                if (response.success) {
                    Message.success('题目删除成功');
                    loadQuestions();
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('删除题目失败:', error);
                Message.error('删除题目失败，请稍后重试');
            }
        }

        // 搜索题目
        function searchQuestions() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const typeFilter = document.getElementById('typeFilter').value;
            
            let filteredQuestions = questions.filter(question => {
                const matchesSearch = (question.content || '').toLowerCase().includes(searchTerm);
                const matchesType = !typeFilter || (question.type || 1).toString() === typeFilter;
                return matchesSearch && matchesType;
            });

            // 临时更新显示
            const questionList = document.getElementById('questionList');
            if (filteredQuestions.length === 0) {
                questionList.innerHTML = `
                    <tr>
                        <td colspan="5" class="text-center">
                            <div class="empty-state">
                                <i>🔍</i>
                                <p>没有找到匹配的题目</p>
                            </div>
                        </td>
                    </tr>
                `;
            } else {
                questionList.innerHTML = filteredQuestions.map(question => {
                    const typeClass = getTypeClass(question.type || 1);
                    const typeText = getTypeText(question.type || 1);
                    const difficultyText = getDifficultyText(question.difficulty);
                    
                    // 构建选项文本
                    const options = [];
                    if (question.optionA) options.push(`A. ${question.optionA}`);
                    if (question.optionB) options.push(`B. ${question.optionB}`);
                    if (question.optionC) options.push(`C. ${question.optionC}`);
                    if (question.optionD) options.push(`D. ${question.optionD}`);
                    const optionsText = options.length > 0 ? options.join('\n') : '暂无选项';

                    return `
                        <tr>
                            <td>
                                <div class="question-info">
                                    <div class="question-icon">❓</div>
                                    <div class="question-details">
                                        <h4>${question.content || '无题目内容'}</h4>
                                        <p style="white-space: pre-line;">${optionsText}</p>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="type-badge ${typeClass}">${typeText}</span>
                            </td>
                            <td>${difficultyText}</td>
                            <td>${formatDate(question.createTime)}</td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn-icon btn-view" onclick="viewQuestion(${question.id})" title="查看详情">
                                        👁️
                                    </button>
                                    <button class="btn-icon btn-edit" onclick="editQuestion(${question.id})" title="编辑">
                                        ✏️
                                    </button>
                                    <button class="btn-icon btn-delete" onclick="deleteQuestion(${question.id})" title="删除">
                                        🗑️
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                }).join('');
            }

            document.getElementById('totalQuestions').textContent = filteredQuestions.length;
        }
    </script>
</body>
</html>